import { NotificationComponent } from './notification.component';
import { Injectable } from '@angular/core';
import { ExDynamicService } from '../shared/services';

export interface Options {
  type?: string;
  offset?: number;
  position?: string;
  iconClass?: string;
  customClass?: string;
  duration?: number;
  showClose?: boolean;
  zIndex?: number;
  onClose?: Function;
}

@Injectable({
  providedIn: 'root'
})
export class NotificationService {
  private root: any;
  private dynamic: any;
  components: Array<any> = [];
  constructor(root: NotificationComponent, dynamic: ExDynamicService) {
    this.root = root;
    this.dynamic = dynamic;
    this.createComponent();
  }

  show(msg: string, title: string) {
    var _this = this;
    var /** @type {?} */ len = this.components.length;
    if (len === 0 || this.components[len - 1].init) {
      this.createComponent();
    }
    // mark the component
    var /** @type {?} */ currentLen = this.components.length;
    var /** @type {?} */ current = this.components[currentLen - 1];
    current.init = true;
    current.instance.setContent(msg, title);
    // init current component
    if (currentLen > 1) {
      var /** @type {?} */ lastInstance = this.components[currentLen - 2].instance;
      current.instance.offset = lastInstance.height + lastInstance.offset + 15;
    }
    current.instance.onDestroy = function () {
      var /** @type {?} */ index = _this.components.findIndex(function (com) { return com.id === current.id; });
      // reflow top style
      _this.components.forEach(function (com, i) {
        if (i <= index)
          return;
        com.instance.offset = com.instance.offset - current.instance.height - 15;
      });
      // component detach and remove element
      _this.dynamic.destroy(current.copy);
      // remove empty item
      _this.components.splice(index, 1);
    };
    var /** @type {?} */ timer = setTimeout(function () {
      current.instance.show();
      clearTimeout(timer);
    }, 0);
  }

  success(msg: string, title: string) {
    this.setOptions({ type: 'success' });
    this.show(msg, title);
  }

  warning(msg: string, title: string) {
    this.setOptions({ type: 'warning' });
    this.show(msg, title);
  }

  info(msg: string, title: string) {
    this.setOptions({ type: 'info' });
    this.show(msg, title);
  }

  error(msg: string, title: string) {
    this.setOptions({ type: 'error' });
    this.show(msg, title);
  }

  setOptions(options: any) {
    if (this.components.length === 0 || this.components[this.components.length - 1].init) {
      this.createComponent();
    }
    var /** @type {?} */ last = this.components[this.components.length - 1];
    last.instance = Object.assign(last.instance, options);
  }

  createComponent() {
    var  com = this.dynamic.generator(NotificationComponent);
    this.components.push({
      instance: com.instance,
      id: com.instance.id,
      copy: com,
      init: false
    });
  }

}
